import pymysql


class MysqlC:

    def __init__(self, host, port,user, password, database):
        self.con = None
        self.arguments = {
            "host": host,
            "port": port,
            "user": user,
            "password": password,
            "database": database,
            "charset": 'utf8'
        }

    def post(self, sql):
        with self:
            try:
                data = self.cursor.execute(sql)
                self.con.commit()

                return data
            except Exception as e:
                self.con.rollback()
                return e

    def get(self, sql, one=None):
        with self:
            try:
                self.cursor.execute(sql)
                if one:
                    return self.cursor.fetchone()
                else:
                    return self.cursor.fetchall()
            except Exception as e:
                return e

    def __enter__(self):
        if self.con is None:
            try:
                self.con = pymysql.connect(**self.arguments)
                self.cursor = self.con.cursor(pymysql.cursors.DictCursor)
            except Exception:
                raise "数据库连接失败！"

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.con.close()
        self.con = None


if __name__ == '__main__':
    mysql = MysqlC('114.116.72.149', 'root', 'Xiaohao@5433', 'fzulab')

    w = mysql.get("select * from  biz_article")
    print(w)